package com.demo.petshop.service.impl;

import com.demo.petshop.entity.*;
import com.demo.petshop.mapper.*;
import com.demo.petshop.service.OrdersService;
import com.demo.petshop.util.Result;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.sqlite.date.DateFormatUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.demo.petshop.entity.table.CartItemsTableDef.CART_ITEMS;
import static com.demo.petshop.entity.table.OrderItemsTableDef.ORDER_ITEMS;
import static com.demo.petshop.entity.table.OrdersTableDef.ORDERS;
import static com.demo.petshop.entity.table.ProductReviewsTableDef.PRODUCT_REVIEWS;
import static com.demo.petshop.entity.table.ProductSpecsTableDef.PRODUCT_SPECS;
import static com.demo.petshop.entity.table.ProductsTableDef.PRODUCTS;
import static com.demo.petshop.entity.table.StoresTableDef.STORES;
import static com.demo.petshop.entity.table.UsersTableDef.USERS;


/**
 * 服务层实现。
 *
 * @author lenovo
 * @since 2025-06-11
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ProductsMapper productsMapper;
    @Autowired
    private OrderItemsMapper orderItemsMapper;
    @Autowired
    private ProductReviewsMapper productReviewsMapper;
    @Autowired
    private StoresMapper storesMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private ProductSpecsMapper productSpecsMapper;
    @Autowired
    private CartItemsMapper cartItemsMapper;
    private String storeName = "storeName";
    private String dateFormat = "yyyy-MM-dd HH:mm:ss.SSS";


    private int getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getUserId();
    }

    @Override
    public Object getByStatus(String status) {

        int userId = getUserId();
        if ("all".equals(status)) {
            // 获取订单基本信息和店铺信息
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.select(ORDERS.ALL_COLUMNS,
                            STORES.NAME.as(storeName),
                            STORES.STORE_ID)
                    .from(ORDERS)
                    .leftJoin(ORDER_ITEMS).on(ORDERS.ORDER_ID.eq(ORDER_ITEMS.ORDER_ID))
                    .leftJoin(PRODUCTS).on(PRODUCTS.PRODUCT_ID.eq(ORDER_ITEMS.PRODUCT_ID))
                    .leftJoin(STORES).on(STORES.STORE_ID.eq(PRODUCTS.STORE_ID))
                    .groupBy(ORDERS.ORDER_ID)
                    .orderBy(ORDERS.ORDER_ID, false)
                    .where(ORDERS.USER_ID.eq(userId));  // 避免重复订单

            List<Orders> orders = ordersMapper.selectListByQuery(queryWrapper);

            // 获取每个订单对应的所有商品项
            for (Orders order : orders) {
                // 查询订单的所有商品项
                QueryWrapper itemsQuery = new QueryWrapper();
                itemsQuery.select(ORDER_ITEMS.ALL_COLUMNS)
                        .from(ORDER_ITEMS)
                        .where(ORDER_ITEMS.ORDER_ID.eq(order.getOrderId()));

                List<OrderItems> orderItems = orderItemsMapper.selectListByQuery(itemsQuery);

                // 获取商品详细信息
                List<Products> productsList = new ArrayList<>();
                for (OrderItems item : orderItems) {
                    ProductSpecs productSpecs = productSpecsMapper.selectOneById(item.getSpecId());
                    item.setSpecValue(productSpecs.getValue());
                    QueryWrapper productQuery = new QueryWrapper();
                    productQuery.select(PRODUCTS.ALL_COLUMNS)
                            .from(PRODUCTS)
                            .where(PRODUCTS.PRODUCT_ID.eq(item.getProductId()));

                    Products product = productsMapper.selectOneByQuery(productQuery);
                    if (product != null) {
                        // 设置商品数量
                        product.setSpecValue(item.getSpecValue());
                        product.setQuantity(item.getQuantity());
                        product.setSpecValue(item.getSpecValue());
                        productsList.add(product);
                    }
                }

                // 设置订单的商品列表
                order.setOrderItems(orderItems);
                order.setProductsItems(productsList);

                // 如果有至少一个商品，设置第一个商品为主商品（兼容旧代码）
                if (!productsList.isEmpty()) {
                    order.setItems(productsList.get(0));
                }

                // 计算订单总金额（商品金额 - 运费 - 折扣）
                double totalAmount = orderItems.stream()
                        .mapToDouble(item -> item.getPrice() * item.getQuantity())
                        .sum() + order.getShippingFee() - order.getDiscountAmount();

                order.setTotalAmount(totalAmount);

                // 更新订单信息
                ordersMapper.update(order);
            }

            return orders;
        } else {
            // 按状态过滤订单
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.select(ORDERS.ALL_COLUMNS,
                            STORES.NAME.as(storeName),
                            STORES.STORE_ID)
                    .from(ORDERS)
                    .leftJoin(ORDER_ITEMS).on(ORDERS.ORDER_ID.eq(ORDER_ITEMS.ORDER_ID))
                    .leftJoin(PRODUCTS).on(PRODUCTS.PRODUCT_ID.eq(ORDER_ITEMS.PRODUCT_ID))
                    .leftJoin(STORES).on(STORES.STORE_ID.eq(PRODUCTS.STORE_ID))
                    .where(ORDERS.STATUS.eq(status))
                    .groupBy(ORDERS.ORDER_ID)
                    .orderBy(ORDERS.ORDER_ID, false)
                    .where(ORDERS.USER_ID.eq(userId));  // 避免重复订单

            List<Orders> orders = ordersMapper.selectListByQuery(queryWrapper);

            // 获取每个订单对应的所有商品项
            for (Orders order : orders) {
                // 查询订单的所有商品项
                QueryWrapper itemsQuery = new QueryWrapper();
                itemsQuery.select(ORDER_ITEMS.ALL_COLUMNS)
                        .from(ORDER_ITEMS)
                        .where(ORDER_ITEMS.ORDER_ID.eq(order.getOrderId()));

                List<OrderItems> orderItems = orderItemsMapper.selectListByQuery(itemsQuery);

                // 获取商品详细信息
                List<Products> productsList = new ArrayList<>();
                for (OrderItems item : orderItems) {

                    ProductSpecs productSpecs = productSpecsMapper.selectOneById(item.getSpecId());
                    item.setSpecValue(productSpecs.getValue());
                    QueryWrapper productQuery = new QueryWrapper();
                    productQuery.select(PRODUCTS.ALL_COLUMNS)
                            .from(PRODUCTS)
                            .where(PRODUCTS.PRODUCT_ID.eq(item.getProductId()));

                    Products product = productsMapper.selectOneByQuery(productQuery);
                    if (product != null) {
                        // 设置商品数量
                        product.setSpecValue(item.getSpecValue());
                        product.setQuantity(item.getQuantity());
                        product.setSpecValue(item.getSpecValue());
                        productsList.add(product);
                    }
                }

                // 设置订单的商品列表
                order.setOrderItems(orderItems);
                order.setProductsItems(productsList);

                // 如果有至少一个商品，设置第一个商品为主商品（兼容旧代码）
                if (!productsList.isEmpty()) {
                    order.setItems(productsList.get(0));
                }

                // 计算订单总金额（商品金额 - 运费 - 折扣）
                double totalAmount = orderItems.stream()
                        .mapToDouble(item -> item.getPrice() * item.getQuantity())
                        .sum() + order.getShippingFee() - order.getDiscountAmount();

                order.setTotalAmount(totalAmount);

                // 更新订单信息
                ordersMapper.update(order);
            }

            return orders;
        }
    }

    @Override
    public Object deleteById(Integer id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        QueryWrapper queryWrapper1 = new QueryWrapper();
        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper.select(ORDERS.ALL_COLUMNS).from(ORDERS)
                .where(ORDERS.ORDER_ID.eq(id));
        queryWrapper1.select(ORDER_ITEMS.ALL_COLUMNS).from(ORDER_ITEMS)
                .where(ORDER_ITEMS.ORDER_ID.eq(id));
        List<OrderItems> orderItems = orderItemsMapper.selectListByQuery(queryWrapper1);
        for (OrderItems orderItems1 : orderItems) {
            queryWrapper2.select(PRODUCTS.ALL_COLUMNS).from(PRODUCTS)
                    .where(PRODUCTS.PRODUCT_ID.eq(orderItems1.getProductId()));
            Products products = productsMapper.selectOneByQuery(queryWrapper2);
            products.setStock(products.getStock()+orderItems1.getQuantity());
            products.setSalesCount(products.getSalesCount()-orderItems1.getQuantity());
            productsMapper.update(products);
        }
        ordersMapper.deleteByQuery(queryWrapper);
        orderItemsMapper.deleteByQuery(queryWrapper1);

        return true;
    }

    @Override
    public Object confirm(Integer id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select(ORDERS.ALL_COLUMNS).from(ORDERS)
                .where(ORDERS.ORDER_ID.eq(id));
        Orders orders = ordersMapper.selectOneByQuery(queryWrapper);
        orders.setStatus("completed");
        Instant instant = Instant.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
        String formatted = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
                .format(formatter);
        orders.setCompletedAt(formatted);
        ordersMapper.update(orders);
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.select(USERS.ALL_COLUMNS).from(USERS)
                .where(USERS.USER_ID.eq(orders.getUserId()));
        Users users = usersMapper.selectOneByQuery(queryWrapper1);
        int totalMount = (orders.getTotalAmount().intValue()) + users.getMemberPoints();
        users.setMemberPoints(totalMount);
        usersMapper.update(users);
        return true;
    }


    @Override
    public Object getInfo(Integer id) {
        // 获取订单基本信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select(ORDERS.ALL_COLUMNS,
                        STORES.NAME.as(storeName),
                        STORES.STORE_ID)
                .from(ORDERS)
                .leftJoin(ORDER_ITEMS).on(ORDERS.ORDER_ID.eq(ORDER_ITEMS.ORDER_ID))
                .leftJoin(PRODUCTS).on(PRODUCTS.PRODUCT_ID.eq(ORDER_ITEMS.PRODUCT_ID))
                .leftJoin(STORES).on(STORES.STORE_ID.eq(PRODUCTS.STORE_ID))
                .where(ORDERS.ORDER_ID.eq(id))
                .groupBy(ORDERS.ORDER_ID);  // 避免重复订单

        Orders order = ordersMapper.selectOneByQuery(queryWrapper);

        if (order != null) {
            // 查询订单的所有商品项
            QueryWrapper itemsQuery = new QueryWrapper();
            itemsQuery.select(ORDER_ITEMS.ALL_COLUMNS)
                    .from(ORDER_ITEMS)
                    .where(ORDER_ITEMS.ORDER_ID.eq(order.getOrderId()));

            List<OrderItems> orderItems = orderItemsMapper.selectListByQuery(itemsQuery);

            // 获取商品详细信息
            List<Products> productsList = new ArrayList<>();
            for (OrderItems item : orderItems) {
                QueryWrapper productQuery = new QueryWrapper();
                productQuery.select(PRODUCTS.ALL_COLUMNS)
                        .from(PRODUCTS)
                        .where(PRODUCTS.PRODUCT_ID.eq(item.getProductId()));
                ProductSpecs productSpecs = productSpecsMapper.selectOneById(item.getSpecId());
                item.setSpecValue(productSpecs.getValue());
                Products product = productsMapper.selectOneByQuery(productQuery);
                if (product != null) {
                    // 设置商品数量
                    product.setQuantity(item.getQuantity());
                    product.setSpecValue(productSpecs.getValue());
                    productsList.add(product);
                }
            }

            // 设置订单的商品列表
            order.setOrderItems(orderItems);
            order.setProductsItems(productsList);

            // 如果有至少一个商品，设置第一个商品为主商品（兼容旧代码）
            if (!productsList.isEmpty()) {
                order.setItems(productsList.get(0));
            }

            // 查询订单评价
            QueryWrapper reviewQuery = new QueryWrapper();
            reviewQuery.select(PRODUCT_REVIEWS.ALL_COLUMNS)
                    .from(PRODUCT_REVIEWS)
                    .where(PRODUCT_REVIEWS.ORDER_ID.eq(id));

            if (!productsList.isEmpty()) {
                reviewQuery.and(PRODUCT_REVIEWS.PRODUCT_ID.eq(productsList.get(0).getProductId()));
            }

            ProductReviews productReviews = productReviewsMapper.selectOneByQuery(reviewQuery);
            order.setProductReviews(productReviews);

            // 计算订单总金额（商品金额 + 运费 - 折扣）
            double totalAmount = orderItems.stream()
                    .mapToDouble(item -> item.getPrice() * item.getQuantity())
                    .sum() + order.getShippingFee() - order.getDiscountAmount();

            order.setTotalAmount(totalAmount);

            // 更新订单信息
            ordersMapper.update(order);
        }

        return order;
    }

    @Override
    public Object createOrder(Orders orders) {
        // 如果没有订单编号，生成一个新的
        if (orders.getOrderNumber() == null || orders.getOrderNumber().isEmpty()) {
            // 使用UUID生成随机订单号
            String orderNumber = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
            orders.setOrderNumber(orderNumber);
        }
        Instant instant = Instant.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
        String formatted = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
                .format(formatter);
        orders.setCreatedAt(formatted);
        // 保存订单基本信息
        ordersMapper.insert(orders);
        // 获取生成的订单ID
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.select(ORDERS.ALL_COLUMNS)
                .from(ORDERS)
                .where(ORDERS.ORDER_NUMBER.eq(orders.getOrderNumber()));
        Orders savedOrder = ordersMapper.selectOneByQuery(queryWrapper1);

        // 处理多个商品项
        if (orders.getOrderItems() != null && !orders.getOrderItems().isEmpty()) {
            int i = 0;
            for (OrderItems item : orders.getOrderItems()) {
                QueryWrapper queryWrapper = new QueryWrapper();
                QueryWrapper queryWrapper2=new QueryWrapper();
                queryWrapper2.select(PRODUCT_SPECS.ALL_COLUMNS).from(PRODUCT_SPECS)
                                .where(PRODUCT_SPECS.VALUE.eq(item.getSpecValue()));
                ProductSpecs productSpecs = productSpecsMapper.selectOneByQuery(queryWrapper2);
                item.setSpecId(productSpecs.getSpecId());
                queryWrapper.select(PRODUCTS.ALL_COLUMNS).from(PRODUCTS)
                        .where(PRODUCTS.PRODUCT_ID.eq(item.getProductId()));
                Products products = productsMapper.selectOneByQuery(queryWrapper);
                Integer stock = products.getStock();
                Integer salesCount = products.getSalesCount();
                products.setStock(stock - orders.getItems().getQuantity());
                products.setSalesCount(salesCount + orders.getItems().getQuantity());
                productsMapper.update(products);
                item.setOrderId(savedOrder.getOrderId());
                item.setPrice(orders.getOrderItems().get(i).getPrice());
                item.setProductId(orders.getOrderItems().get(i).getProductId());
                item.setQuantity(orders.getOrderItems().get(i).getQuantity());
                item.setProductName(products.getName());
                item.setProductImage(orders.getOrderItems().get(i).getProductImage());
                i++;
                orderItemsMapper.insert(item);
            }
        }

        return savedOrder;
    }

    @Override
    public Object createBatchOrders(List<Orders> ordersList) {
        List<Object> results = new ArrayList<>();

        // 为同一商店的订单生成相同的订单编号
        Map<Integer, String> storeOrderNumbers = new HashMap<>();

        // 逐个处理每个商店的订单
        for (Orders order : ordersList) {
            try {
                Integer storeId = order.getStoreId();

                // 检查该商店是否已有订单编号
                if (storeId != null && storeOrderNumbers.containsKey(storeId)) {
                    // 使用已存在的订单编号
                    order.setOrderNumber(storeOrderNumbers.get(storeId));
                } else {
                    // 生成新的订单编号，使用UUID代替RandomStringUtils
                    String orderNumber = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
                    order.setOrderNumber(orderNumber);

                    // 如果有商店ID，记录该商店的订单编号
                    if (storeId != null) {
                        storeOrderNumbers.put(storeId, orderNumber);
                    }
                }

                // 使用已有的创建订单方法处理每个订单
                Object result = createOrder(order);
                results.add(result);
            } catch (Exception e) {
                // 记录错误但继续处理其他订单
                results.add("Error creating order: " + e.getMessage());
            }
        }

        return results;
    }

    @Override
    public Object counts() {
        OrderCountDTO orderCountDTO = new OrderCountDTO();
        int userId = getUserId();
        orderCountDTO.setPendingPayment((int) ordersMapper.selectCountByQuery(new QueryWrapper()
                .where(ORDERS.STATUS.eq("pending_payment"))
                .and(ORDERS.USER_ID.eq(userId))));
        orderCountDTO.setPendingShipment((int) ordersMapper.selectCountByQuery(new QueryWrapper()
                .where(ORDERS.STATUS.eq("pending_shipping"))
                .and(ORDERS.USER_ID.eq(userId))));
        orderCountDTO.setPendingReceipt((int) ordersMapper.selectCountByQuery(new QueryWrapper()
                .where(ORDERS.STATUS.eq("pending_receipt"))
                .and(ORDERS.USER_ID.eq(userId))));
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.select(ORDERS.ALL_COLUMNS).from(ORDERS).join(ORDER_ITEMS).on(ORDERS.ORDER_ID.eq(ORDER_ITEMS.ORDER_ID))
                .where(ORDERS.STATUS.eq("completed"))
                .and(ORDERS.USER_ID.eq(userId))
                .and(ORDER_ITEMS.IS_REVIEWED.eq(0));
        List<Orders> orders = ordersMapper.selectListByQuery(queryWrapper);
        orderCountDTO.setPendingReview(orders.size());
        orderCountDTO.setCancelled((int) ordersMapper.selectCountByQuery(new QueryWrapper()
                .where(ORDERS.STATUS.eq("cancelled"))
                .and(ORDERS.USER_ID.eq(userId))));
        return Result.success(orderCountDTO);
    }

    @Override
    public Object paymentOrder(Orders orders) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select(ORDERS.ALL_COLUMNS).from(ORDERS)
                .where(ORDERS.ORDER_ID.eq(orders.getOrderId()));
        Orders order1 = ordersMapper.selectOneByQuery(queryWrapper);
        order1.setPaymentStatus("已支付");
        order1.setPaidAt(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        order1.setStatus("pending_receipt");
        order1.setPaymentMethod(orders.getPaymentMethod());
        return ordersMapper.update(order1);
    }

    @Override
    public Object cancel(Integer id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select(ORDERS.ALL_COLUMNS).from(ORDERS)
                .where(ORDERS.ORDER_ID.eq(id));
        Orders orders = ordersMapper.selectOneByQuery(queryWrapper);
        orders.setStatus("cancelled");
        Instant instant = Instant.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
        String formatted = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
                .format(formatter);
        orders.setCancelledAt(formatted);

        return ordersMapper.update(orders);
    }

    @Override
    public Object repeatPurchase(List<Products> productsList){
        Result result = null;
        int userId = getUserId();
        for(Products products : productsList){
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1
                    .from(CART_ITEMS)
                    .join(PRODUCT_SPECS).on(CART_ITEMS.SPEC_ID.eq(PRODUCT_SPECS.SPEC_ID))
                    .where(CART_ITEMS.PRODUCT_ID.eq(products.getProductId()))
                    .and(CART_ITEMS.USER_ID.eq(userId));
            CartItems cartItems = cartItemsMapper.selectOneByQuery(queryWrapper1);
            if(cartItems!=null){
                cartItems.setSelected(1);
                cartItems.setQuantity(cartItems.getQuantity()+products.getQuantity());
                result = Result.success(cartItemsMapper.update(cartItems));
            }
            else{
                CartItems newCartItem = new CartItems();
                newCartItem.setUserId(userId);
                QueryWrapper queryWrapper2 = new QueryWrapper();
                queryWrapper2
                        .select(PRODUCT_SPECS.SPEC_ID)
                        .from(PRODUCT_SPECS)
                        .where(PRODUCT_SPECS.VALUE.eq(products.getSpecValue()));
                ProductSpecs productSpecs = productSpecsMapper.selectOneByQuery(queryWrapper2);
                newCartItem.setSpecId(productSpecs.getSpecId());
                newCartItem.setQuantity(products.getQuantity());
                newCartItem.setProductId(products.getProductId());
                newCartItem.setSelected(1);
                newCartItem.setCreatedAt(DateFormatUtils.format(new Date(), "yyyy- -dd HH:mm:ss"));
                result = Result.success(cartItemsMapper.insert(newCartItem));
            }
        }
        return result;
    }
}
